package com.example.socialwebserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.socialwebserver.mapper.FriendMapper;
import com.example.socialwebserver.mapper.LoginMapper;
import com.example.socialwebserver.pojo.*;
import com.example.socialwebserver.service.FriendService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class FriendServiceImpl implements FriendService {
    @Autowired
    FriendMapper friendMapper;
    @Autowired
    LoginMapper loginMapper;

    @Override
    public List<FriendVO> SelectById(Integer id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",id);
        List<FriendDAO>  friendDAOList = friendMapper.selectList(queryWrapper);
        List<FriendVO> friendVOList = new ArrayList<>();
        for(FriendDAO friendDAO: friendDAOList){
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("id",friendDAO.getId());
            LoginDAO  loginDAO = loginMapper.selectOne(queryWrapper1);
            FriendVO friendVO = new FriendVO(friendDAO.getUserId(),friendDAO.getFriendId(),loginDAO.getUserName());
            friendVOList.add(friendVO);
        }
        return friendVOList;
    }

    @Override
    public boolean InsertById(FriendDTO friendDTO) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",friendDTO.getUserId());
        LoginDAO loginDAO = loginMapper.selectOne(queryWrapper);
        queryWrapper.clear();
        queryWrapper.eq("id",friendDTO.getFriendId());
        LoginDAO loginDAO1 = loginMapper.selectOne(queryWrapper);
        queryWrapper.clear();
        queryWrapper.eq("user_id",friendDTO.getUserId());
        queryWrapper.eq("friend_id",friendDTO.getFriendId());
        FriendDAO friendDTO1 = friendMapper.selectOne(queryWrapper);
        if(loginDAO != null && loginDAO1 != null && friendDTO1 == null){
            FriendDAO friendDAO = new FriendDAO();
            BeanUtils.copyProperties(friendDTO, friendDAO);
            System.out.println(friendDAO.toString());
            int row = friendMapper.insert(friendDAO);
            if(row >= 1){
                return true;
            }else {
                return false;
            }
        }else {
            return false;
        }
    }

    @Override
    public boolean DeleteById(FriendDTO  friendDTO) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",friendDTO.getUserId());
        queryWrapper.eq("friend_id",friendDTO.getFriendId());
        int row = friendMapper.delete(queryWrapper);
        if(row >= 1){
            return true;
        }else {
            return false;
        }
    }
}
